package com.longcai.controller.scm;


import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.zxing.WriterException;
import com.longcai.bean.PageHelper;
import com.longcai.entity.homegood.ClyjGoodsHomepage;
import com.longcai.entity.homegood.ClyjGoodsPics;
import com.longcai.entity.homegood.ClyjGoodsSpec;
import com.longcai.entity.homegood.ClyjGoodsVo;
import com.longcai.entity.homepage.ClyjSeckillGoods;
import com.longcai.entity.homepage.GoodsClass;
import com.longcai.entity.scm.ClyjScmGoods;
import com.longcai.entity.scm.ClyjScmGoodsSpec;
import com.longcai.entity.scm.ClyjScmGoodsVo;
import com.longcai.entity.sys.SysRoleUser;
import com.longcai.entity.sys.SysUser;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.scm.ClyjScmGoodsService;
import com.longcai.service.SysRoleUserService;
import com.longcai.service.SysUserService;
import com.longcai.service.goods.ClyjGoodsHomepageService;
import com.longcai.service.goods.ClyjGoodsPicsService;
import com.longcai.service.goods.ClyjSeckillGoodsService;
import com.longcai.util.LoginUser;
import com.longcai.util.OSSUtils;
import com.longcai.util.QRCodeUtils;
import com.longcai.util.UserUtil;

import io.swagger.annotations.ApiOperation;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;

/**
 * <p>
 * 首页商品表 前端控制器
 * </p>
 *
 * @author LWK
 * @since 2019-04-23
 */
@Controller
@RequestMapping("/clyjScmGoods")
public class ClyjScmGoodsController {
	  private Logger logger = LoggerFactory.getLogger(getClass());
	    @Autowired
	    private ClyjScmGoodsService clyjGoodsService;
	    @Autowired
	    private ClyjGoodsPicsService picsService;
	    @Autowired
	    private SysRoleUserService sysRoleUserService;
	    @Autowired
	    private SysUserService sysUserService;
	    @Autowired
	    private ClyjSeckillGoodsService skillService;
	    
	    /**
	     * 查询角色为供应商的用户
	     *
	     * @return
	     */
	    @GetMapping(value="getSupplier")
	    @ResponseBody
	    public List<SysUser> getSupplier() {
	    	QueryWrapper<SysRoleUser> w = new QueryWrapper<SysRoleUser>();
	    	List<SysUser> sysUser = new ArrayList<SysUser>();
	    	w.eq("roleId", 3);
	    	List<SysRoleUser> selectList = sysRoleUserService.selectList(w);
	    	if(selectList==null || selectList.size()==0) {
	            return null;
	        }
	    	for (SysRoleUser sysRoleUser : selectList) {
				//根据用户id获取用户信息
	    		SysUser user = sysUserService.selectById(sysRoleUser.getUserId());
	    		sysUser.add(user);
			}
	         return sysUser;
	    }

	    /**
	     * 分页查询品牌
	     *
	     * @return
	     */
	    @GetMapping(value = "getGoods")
	    @ResponseBody
	    public PageTableResponse getGoods(ClyjScmGoods goods, PageHelper pageHelper) {
	    	Page<ClyjScmGoods> page =new Page<>(pageHelper.getStart(),pageHelper.getLength());
	    	QueryWrapper<ClyjScmGoods> w = new QueryWrapper<ClyjScmGoods>();
	    	if(goods.getGoodsName()!=null && goods.getGoodsName()!="")
	    		w.like("goods_name", goods.getGoodsName());
	    	//获取当前用户信息
	    	LoginUser loginUser = UserUtil.getLoginUser();
	    	if(loginUser.getId()!=1)
	    		w.eq("supplier_id", loginUser.getId());
	    	w.orderByDesc("month_sales");
	        IPage<ClyjScmGoods> sysRoleIPage = clyjGoodsService.selectPage(page, w);
	        PageTableResponse pageTableResponse = new PageTableResponse(sysRoleIPage.getTotal(),
	                sysRoleIPage.getTotal(), sysRoleIPage.getRecords());
	        return pageTableResponse;
	    }

	    /**
	     * 新增商品
	     *
	     * @param goodsClas2s
	     * @param goodsPic2
	     * @param goodsBanner2
	     * @return
	     */
	    @PostMapping(value = "saveGoods")
	    @ResponseBody
	    public boolean save(ClyjScmGoodsVo goodsClas2s, MultipartFile goodsPic2, MultipartFile goodsBanner2) throws IOException, WriterException {
	        if (goodsPic2 != null) {
	            //文档上传oss
	            try {
	                String fileName = goodsPic2.getOriginalFilename();
	                String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
	                InputStream inputStream = goodsPic2.getInputStream();
	                Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODSSCM/PIC/");
	                goodsClas2s.setGoodsPic(uploadByInputStream.get("path").toString());
	            } catch (Exception e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }
	        }
	        if (goodsBanner2 != null) {
	            //文档上传oss
	            try {
	                String fileName = goodsBanner2.getOriginalFilename();
	                String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
	                InputStream inputStream = goodsBanner2.getInputStream();
	                Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODSSCM/BANNER/");
	                goodsClas2s.setGoodsBanner(uploadByInputStream.get("path").toString());
	            } catch (Exception e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }
	        }
	        if (goodsClas2s.getGoodsId() == null || goodsClas2s.getGoodsId() == "" || goodsClas2s.getGoodsId().equals("")) {
	            //新增
	            goodsClas2s.setGoodsId(UUID.randomUUID().toString());
	            goodsClas2s.setCreateTime(LocalDateTime.now());
	            //生成二维码
	            //存放路径
	           /* String realPath = this.getClass().getClassLoader().getResource("static/qrcode").getPath();
	            realPath = realPath.substring(1);
	            //跳转地址
	            String content = "https://www.baidu.com";
	            //名称
	            String name = "image.jpg";
	            File file = QRCodeUtils.testEncode(realPath, content, name);
	            if (file != null) {
	                //文档上传oss
	                try {
	                    String pox = name.substring(name.lastIndexOf(".") + 1);
	                    InputStream inputStream = new FileInputStream(file);
	                    Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, name, "CLYJ/GOODSCODE/");
	                    goodsClas2s.setCode(uploadByInputStream.get("path").toString());
	                } catch (Exception e) {
	                    // TODO Auto-generated catch block
	                    e.printStackTrace();
	                }
	            }*/
	            goodsClas2s.setGoodsStatus("0");
	            this.clyjGoodsService.insert(goodsClas2s);


	        } else {
	            goodsClas2s.setUpdateTime(LocalDateTime.now());
	            this.clyjGoodsService.updateById(goodsClas2s);
	        }
	        //删除分类信息
	        clyjGoodsService.deleteType(goodsClas2s);
	        //新增分类信息
	        clyjGoodsService.insertType(goodsClas2s);
	        //删除规格信息
	        clyjGoodsService.deleteSpec(goodsClas2s);
	        //新增规格信息
	        clyjGoodsService.insertSpec(goodsClas2s);
	        //删除商品图片表
	        clyjGoodsService.deletePics(goodsClas2s);
	        return true;
	    }


	    /**
	     * 根据id获取商品
	     *
	     * @param goodsId
	     * @return
	     */
	    @GetMapping("{goodsId}")
	    @ApiOperation(value = "根据id获取商品")
	    @ResponseBody
	    public Map<String, Object> get(@PathVariable String goodsId) {
	        Map<String, Object> map = new HashMap<String, Object>();
	        ClyjScmGoods selectById = clyjGoodsService.selectById(goodsId);
	        map.put("data", selectById);
	        //查询规格
	        List<ClyjScmGoodsSpec> list = clyjGoodsService.getSpecByGoodsId(goodsId);
	        if (list == null || list.size() == 0) {
	            return map;
	        }
	        List<String> detailList = new ArrayList<String>();
	        List<String> numList = new ArrayList<String>();
	        List<String> sortList = new ArrayList<String>();
	        List<String> idList = new ArrayList<String>();
	        List<List<String>> specPic = new ArrayList<List<String>>();
	        for (ClyjScmGoodsSpec clyjGoodsSpec : list) {
	            detailList.add(clyjGoodsSpec.getSpecDetail());
	            numList.add(String.valueOf(clyjGoodsSpec.getSpecNum()));
	            sortList.add(clyjGoodsSpec.getSpecSort());
	            idList.add(clyjGoodsSpec.getSpecId());
	            //根据specid查询轮播图并将轮播图存入数组
	            QueryWrapper<ClyjGoodsPics> wrapper = new QueryWrapper<ClyjGoodsPics>();
	            wrapper.eq("spec_id", clyjGoodsSpec.getSpecId());
	            wrapper.eq("pic_type", "2");
	            List<ClyjGoodsPics> selectList = picsService.selectList(wrapper);
	            if(selectList==null || selectList.size()==0)
	            	continue;
	            List<String> aList = new ArrayList<String>();
	            for (ClyjGoodsPics clyjGoodsPics : selectList) {
	                aList.add(clyjGoodsPics.getPicUrl());
	            }
	            specPic.add(aList);
	        }
	        ClyjScmGoodsVo s = new ClyjScmGoodsVo();
	        s.setSpecDetail(detailList);
	        s.setSpecNum(numList);
	        s.setSpecSort(sortList);
	        s.setSpecId(idList);
	        s.setSpecPic(specPic);
	        map.put("data2", s);
	        return map;
	    }

	    @GetMapping(value = "goodsId")
	    @ResponseBody
	    @ApiOperation(value = "根据商品id获取类型")
	    public List<GoodsClass> listByBrandId(String goodsId) {
	        return this.clyjGoodsService.listByBrandId(goodsId);
	    }


	    @RequestMapping(value = "saveSpecPic")
	    @ResponseBody
	    public boolean saveSpecPic(ClyjGoodsVo goodsClas2s, MultipartFile[] file0, MultipartFile[] file1, MultipartFile[] file2, MultipartFile[] file3, MultipartFile[] file4) throws Exception {
	        boolean flag = true;
	        List<String> specId = goodsClas2s.getSpecId();
	        if (file0 == null || file0.length == 0) {
	            return flag;
	        }
	        QueryWrapper<ClyjGoodsPics> wrapper = new QueryWrapper<ClyjGoodsPics>();
	        wrapper.in("spec_id", specId);
	        picsService.delete(wrapper);
	        for (MultipartFile multipartFile : file0) {
	            //上传文件
	            String fileName = multipartFile.getOriginalFilename();
	            String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
	            InputStream inputStream = multipartFile.getInputStream();
	            Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODSSCM/SPEC/");
	            //数据库插入数据
	            ClyjGoodsPics a = new ClyjGoodsPics();
	            a.setGoodsId(goodsClas2s.getGoodsId());
	            a.setPicUrl(uploadByInputStream.get("path").toString());
	            a.setSpecId(specId.get(0));
	            a.setId(UUID.randomUUID().toString());
	            a.setPicType("2");
	            a.setPicStatus("1");
	            picsService.insert(a);
	        }
	        if (file1 == null || file1.length == 0) {
	            return flag;
	        }
	        for (MultipartFile multipartFile : file1) {
	            //上传文件
	            String fileName = multipartFile.getOriginalFilename();
	            String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
	            InputStream inputStream = multipartFile.getInputStream();
	            Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODSSCM/SPEC/");
	            //数据库插入数据
	            ClyjGoodsPics a = new ClyjGoodsPics();
	            a.setGoodsId(goodsClas2s.getGoodsId());
	            a.setPicUrl(uploadByInputStream.get("path").toString());
	            a.setSpecId(specId.get(1));
	            a.setId(UUID.randomUUID().toString());
	            a.setPicType("2");
	            a.setPicStatus("1");
	            picsService.insert(a);
	        }
	        if (file2 == null || file2.length == 0) {
	            return flag;
	        }
	        for (MultipartFile multipartFile : file2) {
	            //上传文件
	            String fileName = multipartFile.getOriginalFilename();
	            String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
	            InputStream inputStream = multipartFile.getInputStream();
	            Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODSSCM/SPEC/");
	            //数据库插入数据
	            ClyjGoodsPics a = new ClyjGoodsPics();
	            a.setGoodsId(goodsClas2s.getGoodsId());
	            a.setPicUrl(uploadByInputStream.get("path").toString());
	            a.setSpecId(specId.get(2));
	            a.setPicType("2");
	            a.setPicStatus("1");
	            a.setId(UUID.randomUUID().toString());
	            picsService.insert(a);
	        }
	        if (file3 == null || file3.length == 0) {
	            return flag;
	        }
	        for (MultipartFile multipartFile : file3) {
	            //上传文件
	            String fileName = multipartFile.getOriginalFilename();
	            String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
	            InputStream inputStream = multipartFile.getInputStream();
	            Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODSSCM/SPEC/");
	            //数据库插入数据
	            ClyjGoodsPics a = new ClyjGoodsPics();
	            a.setGoodsId(goodsClas2s.getGoodsId());
	            a.setPicUrl(uploadByInputStream.get("path").toString());
	            a.setSpecId(specId.get(3));
	            a.setPicType("2");
	            a.setPicStatus("1");
	            a.setId(UUID.randomUUID().toString());
	            picsService.insert(a);
	        }
	        if (file4 == null || file0.length == 4) {
	            return flag;
	        }
	        for (MultipartFile multipartFile : file4) {
	            //上传文件
	            String fileName = multipartFile.getOriginalFilename();
	            String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
	            InputStream inputStream = multipartFile.getInputStream();
	            Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODSSCM/SPEC/");
	            //数据库插入数据
	            ClyjGoodsPics a = new ClyjGoodsPics();
	            a.setGoodsId(goodsClas2s.getGoodsId());
	            a.setPicUrl(uploadByInputStream.get("path").toString());
	            a.setSpecId(specId.get(4));
	            a.setPicType("2");
	            a.setPicStatus("1");
	            a.setId(UUID.randomUUID().toString());
	            picsService.insert(a);
	        }
	        return flag;
	    }
	    
	    @DeleteMapping("{goodsId}")
	    @ApiOperation(value = "删除商品")
	    @ResponseBody
	    @PreAuthorize("hasAuthority('goods:good:del')")
	    public void delete(@PathVariable String goodsId) {
	        this.clyjGoodsService.deleteById(goodsId);
	        //删除商品分类中间表的数据
	        ClyjScmGoodsVo goodsClas2s = new ClyjScmGoodsVo();
	        goodsClas2s.setGoodsId(goodsId);
	        clyjGoodsService.deleteType(goodsClas2s);
	        //删除商品规格中间表的数据
	        clyjGoodsService.deleteSpec(goodsClas2s);
	        //删除商品图片中间表的数据
	        clyjGoodsService.deletePics(goodsClas2s);
	    }
}

